package com.agung.wonogirimaps.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.agung.wonogirimaps.entity.Category;
import com.agung.wonogirimaps.entity.Hotel;
import com.agung.wonogirimaps.entity.Lokasi;
import com.agung.wonogirimaps.entity.RumahMakan;

/**
 * JSONAdapter class class untuk menangani pertukaran data pada webservice
 * 
 * @author pratama
 * 
 */
public class JSONAdapter
{
	private static final String	TAG					= JSONAdapter.class
															.getName();
	private InputStream			is					= null;
	private JSONObject			jsonObject			= null;
	private String				json				= "";

	private static final String	TAG_LOCATION		= "location";
	private static final String	TAG_CATEGORY		= "category";
	private static final String	TAG_SEARCH			= "search";
	private static final String	TAG_HOTEL			= "hotel";
	private static final String	TAG_RUMAH_MAKAN		= "rumahmakan";
	private static final String	TAG_ID				= "id";
	private static final String	TAG_NAMA			= "nama";
	private static final String	TAG_DESC			= "desc";
	private static final String	TAG_LAT				= "lat";
	private static final String	TAG_LNG				= "lng";
	private static final String	TAG_ALAMAT			= "alamat";
	private static final String	TAG_TELP			= "telp";
	private static final String	TAG_GAMBAR			= "gambar";
	private static final String	TAG_FASILITAS		= "fasilitas";
	private static final String	TAG_TELEPON			= "telp";
	private static final String	TAG_KELAS			= "kelas";
	private static final String	TAG_JENISMAKANAN	= "jenis_makanan";
	private static final String	TAG_RATE			= "rate";
	private static final String	TAG_STATUS			= "status";
	private static final String	TAG_EMAIL			= "email";
	private static final String	TAG_KOMENTAR		= "komentar";

	public JSONObject getJSONFromURL(String url)
	{
		try
		{
			System.setProperty("http.keepAlive", "false");
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);

			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (ClientProtocolException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}

		try
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);

			StringBuilder sb = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null)
			{
				sb.append(line + "\n");
			}

			is.close();
			json = sb.toString();
		} catch (Exception e)
		{
			Utils.TRACE(TAG, "error buffered reader " + e.getMessage());
		}

		try
		{
			Utils.TRACE("jsonadapter", "hasil json ->" + json);
			jsonObject = new JSONObject(json);

		} catch (JSONException e)
		{
			Utils.TRACE(TAG, "Error jsonObject");
		}

		return jsonObject;
	}

	/**
	 * Method untuk mengambil semua category
	 * 
	 * @param obj
	 * @return listCategory
	 */
	public List<Category> getAllCategory(JSONObject obj)
	{
		List<Category> listCategory = new ArrayList<Category>();
		try
		{
			JSONArray jsonArray = obj.getJSONArray(TAG_CATEGORY);
			for (int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject jObj = jsonArray.getJSONObject(i);
				Category cat = new Category();
				cat.setId(jObj.getInt(TAG_ID));
				cat.setName(jObj.getString(TAG_NAMA));

				Utils.TRACE(TAG, cat.getName());

				listCategory.add(cat);
			}
		} catch (Exception e)
		{
			Utils.TRACE(TAG, "error ambil category " + e.getMessage());
		}
		return listCategory;
	}

	/**
	 * Method untuk mengambil semua lokasi
	 * 
	 * @param obj
	 * @return listLokasi
	 */
	public List<Lokasi> getAllLocation(JSONObject obj)
	{
		Utils.TRACE("JSONAdapter", "get all location");
		List<Lokasi> listLokasi = new ArrayList<Lokasi>();
		try
		{
			JSONArray jsonArray = obj.getJSONArray(TAG_LOCATION);
			for (int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject jObj = jsonArray.getJSONObject(i);

				Lokasi lokasi = new Lokasi();
				lokasi.setId(jObj.getInt(TAG_ID));
				lokasi.setNama(jObj.getString(TAG_NAMA));
				lokasi.setDeskripsi(jObj.getString(TAG_DESC));
				lokasi.setLat(jObj.getDouble(TAG_LAT));
				lokasi.setLng(jObj.getDouble(TAG_LNG));
				lokasi.setAlamat(jObj.getString(TAG_ALAMAT));
				lokasi.setTelp(jObj.getString(TAG_TELP));
				lokasi.setRate((float) jObj.getDouble(TAG_RATE));

				JSONArray arrayGambar = jObj.getJSONArray(TAG_GAMBAR);
				List<String> listGambar = new ArrayList<String>();
				for (int j = 0; j < arrayGambar.length(); j++)
				{
					listGambar.add(arrayGambar.getString(j));
					Utils.TRACE(TAG,
							"gambar ambil -> " + arrayGambar.getString(j));
				}
				lokasi.setGambar(listGambar);
				Utils.TRACE("jsonadapter", "panjang list gambar : "
						+ listGambar.size());
				Utils.TRACE("jsonadapter", "panjang list gambar pada objeck : "
						+ lokasi.getGambar().size());

				JSONArray arrayKomentar = jObj.getJSONArray(TAG_KOMENTAR);
				List<String> listKomentar = new ArrayList<String>();
				for (int k = 0; k < arrayKomentar.length(); k++)
				{
					listKomentar.add(arrayKomentar.getString(k));
				}
				lokasi.setKomentar(listKomentar);

				listLokasi.add(lokasi);
			}
		} catch (Exception e)
		{
			Utils.TRACE(TAG, "Error ambil semua lokasi" + e.getMessage());
		}

		// diurutin dari besar ke kecil
		Utils.sortingLokasiDESC(listLokasi);

		return listLokasi;
	}

	/**
	 * cari lokasi
	 * 
	 * @param obj
	 * @return
	 */
	public List<Lokasi> getLocationBySearch(JSONObject obj)
	{
		List<Lokasi> listLokasi = new ArrayList<Lokasi>();
		try
		{
			JSONArray jsonArray = obj.getJSONArray(TAG_SEARCH);
			for (int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject jObj = jsonArray.getJSONObject(i);

				Lokasi lokasi = new Lokasi();
				lokasi.setId(jObj.getInt(TAG_ID));
				lokasi.setNama(jObj.getString(TAG_NAMA));
				lokasi.setDeskripsi(jObj.getString(TAG_DESC));
				lokasi.setLat(jObj.getDouble(TAG_LAT));
				lokasi.setLng(jObj.getDouble(TAG_LNG));
				lokasi.setAlamat(jObj.getString(TAG_ALAMAT));
				lokasi.setTelp(jObj.getString(TAG_TELP));
				lokasi.setRate((float) jObj.getDouble(TAG_RATE));

				JSONArray arrayGambar = jObj.getJSONArray(TAG_GAMBAR);
				List<String> listGambar = new ArrayList<String>();
				for (int j = 0; j < arrayGambar.length(); j++)
				{
					listGambar.add(arrayGambar.getString(j));
					Utils.TRACE(TAG,
							"gambar ambil -> " + arrayGambar.getString(j));
				}
				lokasi.setGambar(listGambar);

				JSONArray arrayKomentar = jObj.getJSONArray(TAG_KOMENTAR);
				List<String> listKomentar = new ArrayList<String>();
				for (int k = 0; k < arrayKomentar.length(); k++)
				{
					listKomentar.add(arrayKomentar.getString(k));
				}
				lokasi.setKomentar(listKomentar);

				listLokasi.add(lokasi);
			}
		} catch (Exception e)
		{
			Utils.TRACE(TAG, "Error ambil semua lokasi" + e.getMessage());
		}

		// diurutin dari besar ke kecil
		Utils.sortingLokasiDESC(listLokasi);

		return listLokasi;
	}

	/**
	 * Get All Hotel
	 * 
	 * @param obj
	 * @return
	 */
	public List<Hotel> getAllHotel(JSONObject obj)
	{
		List<Hotel> hotel = new ArrayList<Hotel>();
		try
		{
			JSONArray jArray = obj.getJSONArray(TAG_HOTEL);
			Utils.TRACE("JsonAdapter", "panjang array json " + jArray.length());
			for (int i = 0; i < jArray.length(); i++)
			{
				JSONObject jObj = jArray.getJSONObject(i);
				Hotel h = new Hotel();
				h.setId(jObj.getInt(TAG_ID));
				h.setNama(jObj.getString(TAG_NAMA));
				h.setAlamat(jObj.getString(TAG_ALAMAT));
				h.setFasilitas(jObj.getString(TAG_FASILITAS));
				h.setTelepon(jObj.getString(TAG_TELEPON));
				h.setKelas(jObj.getString(TAG_KELAS));
				JSONArray arrayGambar = jObj.getJSONArray(TAG_GAMBAR);
				h.setGambar(arrayGambar.getString(0));
				h.setLat(jObj.getDouble(TAG_LAT));
				h.setLng(jObj.getDouble(TAG_LNG));
				Utils.TRACE(TAG, h.getNama());

				hotel.add(h);
			}
		} catch (JSONException e)
		{
			Utils.TRACE(TAG, "error ambil hotel " + e.getMessage());
		}
		return hotel;
	}

	/**
	 * Get all rumah makan
	 * 
	 * @param obj
	 * @return
	 */
	public List<RumahMakan> getAllRumahMakan(JSONObject obj)
	{
		List<RumahMakan> listRM = new ArrayList<RumahMakan>();
		try
		{
			JSONArray jArray = obj.getJSONArray(TAG_RUMAH_MAKAN);
			for (int i = 0; i < jArray.length(); i++)
			{
				JSONObject jObj = jArray.getJSONObject(i);

				RumahMakan rm = new RumahMakan();
				rm.setId(jObj.getInt(TAG_ID));
				rm.setNama(jObj.getString(TAG_NAMA));
				rm.setAlamat(jObj.getString(TAG_ALAMAT));
				rm.setMenu(jObj.getString(TAG_JENISMAKANAN));
				
				rm.setLat(jObj.getDouble(TAG_LAT));
				rm.setLng(jObj.getDouble(TAG_LNG));
				JSONArray arrayGambar = jObj.getJSONArray(TAG_GAMBAR);
				rm.setImage(arrayGambar.getString(0));

				Utils.TRACE(TAG, rm.getMenu());

				listRM.add(rm);

			}
		} catch (JSONException e)
		{
			Utils.TRACE(TAG, e.getMessage());
		}
		return listRM;
	}

	/**
	 * check email user, ada atau tidak di daftar user
	 * 
	 * @param obj
	 * @return true OR false
	 */
	public boolean checkEmail(JSONObject obj)
	{
		try
		{
			return (obj.getString(TAG_STATUS).equals("succes")) ? true : false;
		} catch (Exception e)
		{
			Utils.TRACE(TAG, "error check email " + e.getMessage());
		}
		return false;

	}

	public boolean giveRate(JSONObject obj)
	{
		try
		{
			return (obj.getString(TAG_STATUS).equals("succes")) ? true : false;
		} catch (Exception e)
		{
			Utils.TRACE(TAG, "error give rate" + e.getMessage());
		}
		return false;

	}
}
